package com.example.springbootdemo.text;

import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;

public class CosineSimilarity {

    /**
     * 计算两个字符串的余弦相似度。
     * 
     * @param text1 第一个文本字符串
     * @param text2 第二个文本字符串
     * @return 余弦相似度（0到1之间）
     */
    public static double computeCosineSimilarity(String text1, String text2) {
        Map<String, Integer> freq1 = getTermFrequency(text1);
        Map<String, Integer> freq2 = getTermFrequency(text2);
        
        // 获取所有词汇的并集
        Map<String, Integer> allTerms = new HashMap<>(freq1);
        freq2.keySet().forEach(term -> allTerms.putIfAbsent(term, 0));
        
        // 构建向量
        int[] vector1 = new int[allTerms.size()];
        int[] vector2 = new int[allTerms.size()];
        int index = 0;
        for (String term : allTerms.keySet()) {
            vector1[index] = freq1.getOrDefault(term, 0);
            vector2[index] = freq2.getOrDefault(term, 0);
            index++;
        }
        
        // 计算余弦相似度
        double dotProduct = 0.0;
        double normA = 0.0;
        double normB = 0.0;
        for (int i = 0; i < vector1.length; i++) {
            dotProduct += vector1[i] * vector2[i];
            normA += Math.pow(vector1[i], 2);
            normB += Math.pow(vector2[i], 2);
        }
        
        if (normA == 0.0 || normB == 0.0) {
            return 0.0;
        }
        
        return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
    }
    
    /**
     * 计算文本的词频。
     * 
     * @param text 输入文本
     * @return 词频映射
     */
    private static Map<String, Integer> getTermFrequency(String text) {
        String[] tokens = text.toLowerCase().replaceAll("[^a-z0-9\\s]", "").split("\\s+");
        Map<String, Integer> freqMap = new HashMap<>();
        for (String token : tokens) {
            if (!token.isEmpty()) {
                freqMap.put(token, freqMap.getOrDefault(token, 0) + 1);
            }
        }
        return freqMap;
    }
    
    public static void main(String[] args) {
//        String text1 = "我喜欢学习人工智能和机器学习。";
//        String text2 = "机器学习和人工智能是我的兴趣所在。";
        String text1 ="[camel-paycenter-payin],[2024-10-09 11:26:14 {TT-event-2} {872  } SettlementGoodsGatewayRepositoryImpl:34 - PF20241009112214139000137 (PAY) 未发现网关货款应结，不更新入库], ";
//        String text2 ="[camel-paycenter-payin],[2021-01-09 11:26:14 {TT-event-10} {899  } SettlementGoodsGatewayRepositoryImpl:55 - PF20241009104755823000128 (PAY) 未发现网关货款应结，不更新入库], ";
        String text2 = "[camel-trader-payin],[Wed Oct 09 11:40:14 CST 2024:java.lang.RuntimeException:result is empty],msg:[at com.dhpay.serviceimpl.accounting.OutAccountStatisticsServiceImpl.standingBookSftpUpload(OutAccountStatisticsServiceImpl.java:242)\t],";

        
        double similarity = computeCosineSimilarity(text1, text2);
        System.out.printf("余弦相似度: %.4f\n", similarity);
    }
}
